package vip.geeker.iotms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.geeker.iotms.dto.UserDto;
import vip.geeker.iotms.help.BusinessException;
import vip.geeker.iotms.help.BusinessResponseCode;
import vip.geeker.iotms.persistance.mapper.UserMapper;
import vip.geeker.iotms.persistance.model.User;
import vip.geeker.iotms.service.IUserService;
import vip.geeker.iotms.utils.Md5Utils;
import vip.geeker.iotms.utils.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class UserService extends ServiceImpl<UserMapper, User> implements IUserService {
    public static final String SALT = "just do it !";

    @Resource
    private UserMapper userMapper;

    public UserDto auth(User user) {
        String pwd = encryptPwd(user.getLoginName(), user.getLoginPwd());
        user.setLoginPwd(pwd);
        user.setLocked(false);
        UserDto userDto = userMapper.getUser(user);
        if (ObjectUtils.isNullOrEmpty(userDto)) {
            throw new RuntimeException("用户名或密码错误！");
        }
        userMapper.updateByPrimaryKeySelective(User.builder().id(userDto.getId()).lastLoginTime(new Date()).build());
        return userDto;
    }

    public boolean addUser(User user) {
        User validParam = new User();
        validParam.setLoginName(user.getLoginName());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(validParam);
        List<User> userList = userMapper.selectList(queryWrapper);
        if (ObjectUtils.isNotNullAndEmpty(userList)) {
            throw new BusinessException(BusinessResponseCode.BAD_REQUEST, "已存在相同的登录名！");
        }
        String pwd = encryptPwd(user.getLoginName(), user.getLoginPwd());
        user.setLoginPwd(pwd);
        user.setLocked(false);
        user.setCreateTime(new Date());
        return userMapper.insertSelective(user) == 1;
    }

    private String encryptPwd(String loginName, String originPwd) {
        return Md5Utils.getMD5(SALT.concat(loginName).concat(originPwd));
    }

    public PageInfo<UserDto> getUserPage(User user) {
        PageHelper.startPage(user.getPageNo(), user.getPageSz());
        List<UserDto> list = userMapper.getUserList(user);
        return new PageInfo<>(list);
    }

    public User selectByPrimaryKey(Integer id){
        return userMapper.selectByPrimaryKey(id);
    }

    public boolean updateUser(User user){
        if(ObjectUtils.isNotNullAndEmpty(user.getLoginPwd())) {
            String pwd = encryptPwd(user.getLoginName(), user.getLoginPwd());
            user.setLoginPwd(pwd);
        }
        return userMapper.updateByPrimaryKeySelective(user)==1;
    }

}
